package com.md.api.service.impl;

import com.md.api.common.config.RedisKeys;
import com.md.api.common.utils.*;
import com.md.api.dao.*;
import com.md.api.entity.*;
import com.md.api.entity.dto.ComposeQueryDto;
import com.md.api.entity.enums.UserStatus;
import com.md.api.entity.util.Page;
import com.md.api.service.UserSevice;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.UUID;
import java.util.regex.Pattern;

/**
 * @Author liujie
 * @ClassName UserServiceImpl
 **/

@Slf4j
@Service
public class UserServiceImpl implements UserSevice {
    @Resource
    UserPointRecordMapper pointsRecordMapper;
    @Resource
    UserBalanceRecordMapper balanceRecordMapper;
    @Resource
    RedisUtil redisUtil;
    @Resource
    UserMapper userMapper;
    @Resource
    UserMessageMapper userMessageMapper;
    @Resource
    TokenUtil tokenUtil;
    @Resource
    UserWithdrawalRecordMapper withdrawalRecordMapper;
    @Resource
    UserCouponRecordMapper couponRecordMapper;

    @Value("${common-key}")
    String commonKey;
    @Resource
    UserBankMapper bankMapper;


    @Override
    public HttpResult getInfo(HttpServletRequest request) {
        String userId = tokenUtil.getUserId(request);
        UserInfo dbuser = userMapper.getByUserId(userId);
        if (null==dbuser){
            return HttpResult.fail("账号不存在！");
        }
        //优惠券数量
        List<UserCouponRecord> userCouponRecords = couponRecordMapper.myCoupon(userId, 0,null);
        dbuser.setCouponCount(userCouponRecords.size());
        String token = request.getHeader("token");
        dbuser.setToken(token);
        redisUtil.set(RedisKeys.getUserTokenInfoKey(token),dbuser);
        return new HttpResult(dbuser);
    }

    @Override
    public HttpResult register(HttpServletRequest request,  UserInfo user) {
        try {
            String code;
            // 查看是否有缓存
            code = redisUtil.getString(RedisKeys.SMS_CODE.redisKey()  + user.getEmail());
            if(VerifyUtil.isMiss(code)){
                return HttpResult.fail("验证码已过期!");
            }
            if(!code.equalsIgnoreCase(user.getMessageCode())){
                return HttpResult.fail("验证码错误!");
            }
            UserInfo dbUserPhone = userMapper.findByPhone(user.getPhone());
            if (dbUserPhone!=null&&dbUserPhone.getStatus()==UserStatus.LOG_OFF.value()){
                userMapper.updateStatus(dbUserPhone.getUserId(),UserStatus.NORMAL.value());
                return HttpResult.OK;
            }
            if (dbUserPhone!=null&&dbUserPhone.getStatus()!=UserStatus.LOG_OFF.value()){
                return HttpResult.fail("該手機號已被使用！");
            }
            UserInfo dbUserEmail = userMapper.findByEmail(user.getEmail());
            if (dbUserEmail!=null&&dbUserEmail.getStatus()==UserStatus.LOG_OFF.value()){
                userMapper.updateStatus(dbUserEmail.getUserId(),UserStatus.NORMAL.value());
                return HttpResult.OK;
            }
            if (dbUserEmail!=null&&dbUserEmail.getStatus()!=UserStatus.LOG_OFF.value()){
                return HttpResult.fail("該郵箱已被使用！");
            }
            String userId = Md5Utils.encode(user.getEmail());
            user.setUserId(userId);
            if(StringUtils.isEmpty(user.getNickName())){
                user.setNickName(user.getEmail());
            }
            userMapper.register(user);
        }catch (Exception e){
            e.printStackTrace();
            return HttpResult.fail("注册失败！");
        }
        return HttpResult.OK;
    }

    @Override
    public HttpResult updateBaseInfo(HttpServletRequest request, UserInfo user) {
        String userId = tokenUtil.getUserId(request);
        user.setUserId(userId);
        UserInfo dbuser = userMapper.getByUserId(userId);

        if (StringUtils.isNotEmpty(dbuser.getBirthDay())
        &&StringUtils.isNotEmpty(user.getBirthDay())
        &&!dbuser.getBirthDay().equals(user.getBirthDay())){
            return HttpResult.fail("生日不可修改!");
        }
        userMapper.updateBase(user);
        String token = request.getHeader("token");
        dbuser.setToken(token);
        redisUtil.set(RedisKeys.getUserTokenInfoKey(token),dbuser);
        return new HttpResult(dbuser);
    }

    @Override
    public HttpResult userLogin(HttpServletRequest request, UserInfo user) {
        try {
            String code;
            // 查看是否有缓存
//            code = redisUtil.getString(RedisKeys.SMS_CODE.redisKey()  + user.getPhone());
//            if(VerifyUtil.isMiss(code)){
//                return HttpResult.fail("验证码已过期!");
//            }
//            if(!code.equalsIgnoreCase(user.getMessageCode())){
//                return HttpResult.fail("验证码错误!");
//            }
            UserInfo dbuser = null;
            Pattern EMAIL_PATTERN = Pattern.compile(
                            "[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
                                    "\\@" +
                                    "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
                                    "(" +
                                    "\\." +
                                    "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
                                    ")+"
                    );
            boolean isEmail = EMAIL_PATTERN.matcher(user.getPhone()).matches();
            if (isEmail){
                dbuser = userMapper.loginByEmail(user.getPhone());
                if (null==dbuser){
                    return HttpResult.fail("账号不存在！");
                }
            }else{
                dbuser = userMapper.loginByPhone(user.getPhone());
                if (null==dbuser){
                    return HttpResult.fail("账号不存在！");
                }
            }
            String loginToken = UUID.randomUUID().toString().replaceAll("-", "");
            dbuser.setToken(loginToken);
            redisUtil.set(RedisKeys.getUserTokenInfoKey(loginToken),dbuser);
            return new HttpResult(dbuser);
        }catch (Exception e){
            e.printStackTrace();
            return HttpResult.fail("登录失败！");
        }
    }

    @Override
    public HttpResult loginOut(HttpServletRequest request) {

        redisUtil.removeKey(RedisKeys.getUserTokenInfoKey(request.getHeader("token")));
        return HttpResult.OK;
    }

    @Override
    public HttpResult logOff(HttpServletRequest request) {

        redisUtil.removeKey(RedisKeys.getUserTokenInfoKey(request.getHeader("token")));
        String userId = tokenUtil.getUserId(request);
        userMapper.updateStatus(userId, UserStatus.LOG_OFF.value());
        //清空ftp账号及照片


        //清空相册


        return HttpResult.OK;
    }




    @Override
    public HttpResult pointDetails(HttpServletRequest request, ComposeQueryDto qto) {
        Page page = qto.getPage();
        page.initPagingData(UserPointsRecord.class);
        String userId = tokenUtil.getUserId(request);
        List<UserPointsRecord> pointDetails = pointsRecordMapper.pointDetails(userId);
        page.setResult(pointDetails);
        return new HttpResult(page);
    }

    @Override
    public HttpResult balanceDetails(HttpServletRequest request, ComposeQueryDto qto) {
        Page page = qto.getPage();
        page.initPagingData(UserBalanceRecord.class);
        String userId = tokenUtil.getUserId(request);
        List<UserBalanceRecord> balanceDetails = balanceRecordMapper.balanceDetails(userId);
        page.setResult(balanceDetails);
        return new HttpResult(page);
    }

    @Override
    public HttpResult myPoint(HttpServletRequest request) {
        String userId = tokenUtil.getUserId(request);
        Double point = pointsRecordMapper.getPoint(userId);
        return new HttpResult(point);
    }

    @Override
    public HttpResult myBalance(HttpServletRequest request) {
        String userId = tokenUtil.getUserId(request);
        Double point = balanceRecordMapper.getBalance(userId);
        return new HttpResult(point);
    }

    @Override
    public HttpResult myBank(HttpServletRequest request) {
        String userId = tokenUtil.getUserId(request);
        List<UserBank> banks = bankMapper.myBank(userId);
        return new HttpResult(banks);
    }


    @Override
    public HttpResult addBank(HttpServletRequest request, UserBank bank) {
        String userId = tokenUtil.getUserId(request);
        List<UserBank> banks = bankMapper.myBank(userId);
        if (!CollectionUtils.isEmpty(banks)){
            return HttpResult.fail("您已添加过银行卡！");
        }
        String bankId = IdUtil.uuid();
        bank.setBankId(bankId);
        bank.setUserId(userId);
        bankMapper.insert(bank);
        return HttpResult.OK;
    }

    @Override
    public HttpResult updateBank(HttpServletRequest request, UserBank bank) {
        bankMapper.update(bank);
        return HttpResult.OK;
    }


    @Override
    public HttpResult myDrawal(HttpServletRequest request, ComposeQueryDto qto) {
        Page page = qto.getPage();
        page.initPagingData(UserWithdrawalRecord.class);
        String userId = tokenUtil.getUserId(request);
        List<UserWithdrawalRecord> withdrawalRecords = withdrawalRecordMapper.list(userId);
        page.setResult(withdrawalRecords);
        return new HttpResult(page);
    }

    @Override
    public HttpResult withdrawal(HttpServletRequest request, UserWithdrawalRecord drawal) {
        String userId = tokenUtil.getUserId(request);
        UserInfo user = userMapper.getByUserId(userId);
        if (null==user.getBalance()||user.getBalance()<drawal.getWithdrawalMoney()){
            return HttpResult.fail("您的佣金余额不足！");
        }
        drawal.setUserId(userId);
        drawal.setWithdrawalId(IdUtil.uuid());
        withdrawalRecordMapper.insert(drawal);
        return HttpResult.OK;
    }


    @Override
    public HttpResult setParent(HttpServletRequest request, UserInfo userInfo) {
        String userId = tokenUtil.getUserId(request);
        UserInfo user = userMapper.getByUserId(userId);
        UserInfo parentUser = userMapper.getByUserId(userInfo.getParentUserId());
        if (StringUtils.isEmpty(user.getParentUserId())&&!userInfo.getParentUserId().equals(user.getUserId())){
            userMapper.setParent(userId,parentUser.getUserId(),parentUser.getNickName(),parentUser.getPhone());
        }
        return HttpResult.OK;
    }


    @Override
    public HttpResult getNext(HttpServletRequest request,ComposeQueryDto queryDto) {
        String userId = queryDto.getUserId();
        if (StringUtils.isEmpty(userId)){
            userId = tokenUtil.getUserId(request);
        }
        Page page = queryDto.getPage();
        page.initPagingData(UserInfo.class);
        List<UserInfo> nextUsers = userMapper.getByParentUserId(userId);
        page.setResult(nextUsers);
        return new HttpResult(page);
    }
    @Override
    public HttpResult message(HttpServletRequest request,ComposeQueryDto queryDto) {
        String userId = tokenUtil.getUserId(request);
        Page page = queryDto.getPage();
        page.initPagingData(UserMessage.class);
        List<UserMessage> nextUsers = userMessageMapper.getByUserId(userId);
        page.setResult(nextUsers);
        return new HttpResult(page);
    }

    @Override
    public HttpResult messageDetail(HttpServletRequest request,UserMessage message) {
        UserMessage mess = userMessageMapper.getDetail(message.getId());
        userMessageMapper.read(message.getId());
        return new HttpResult(mess);
    }

    @Override
    public HttpResult unbindParent(UserInfo user) {
        userMapper.unbindParent(user.getUserId());
        return HttpResult.OK;
    }

}
